class texWriter:
    
    def writeTexTable(self,head,line,name):
        l = 'llllllllllllllllllllllllllllllllll'
        line = self.highlight(line)
        file = open(name, 'w')
        file.writelines('\n'.join(['\\begin{center}''\\begin{table}[htp]','\\centering']))
        file.write('\\begin{tabular}{'+ l[:len(head)] +'} \\hline \n')
        file.write(self.tStr(' & '.join(head) + '\\\\ \\hline  \n'))
        file.write('\\\\ \n'.join([self.tStr(' & '.join(s)) for s in line]))
        file.writelines('\n'.join(['\\\\ \\hline','\\end{tabular}','\\end{table}','\\end{center}']))
        file.close()
    
    def writeSortedTables(self,head,line,name,s):
        #construct groups of lines
        fields = {}
        for l in line:
            if fields.has_key(l[s]):
                fields[l[s]].append(l)
            else:
                fields[l[s]] = [l]
        #start writing
        l = 'llllllllllllllllllllllllllllllllll'
        file = open(name, 'w')
        file.writelines('\n'.join(['\\begin{center}''\\begin{table}[htp]','\\centering']))
        file.write('\\begin{tabular}{'+ l[:len(head)] +'} \\hline \n')
        file.write(self.tStr(' & '.join(head) + '\\\\ \\hline  \n'))     
        #print each section
        i = 0
        for s in fields.keys():
            i +=1
            lines = fields[s]
            lines = self.highlight(lines)
            file.write('\\\\ \n'.join([self.tStr(' & '.join(ss)) for ss in lines]))
            if not i==len(fields.keys()):
                file.write('\\\\ \\hline \n')
            else:
                file.write('\\ \n') 
            
        file.writelines('\n'.join(['\\\\ \\hline','\\end{tabular}','\\caption{Sorted by}','\\end{table}','\\end{center}']))
        file.close()
    
    
    #highlights the highest values of a set of runs
    def highlight(self,line):
        m = []
        for i in xrange(3,len(line[0])):
            m.append(max([s[i] for s in line]))
        for s in line:
            for i in xrange(3,len(line[0])):
                if s[i]==m[i-3]:
                    s[i] = '\\textbf{'+ m[i-3] +'}'
        return line            
            
        
        
    #make into valid tex string
    def tStr(self,st):
        return st.replace('_',' ')